package com.goddess.yeecolor.fragment.CollegeFragmentGraceAllFragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;

import com.goddess.yeecolor.Modle.PublicModle;
import com.goddess.yeecolor.R;
import com.goddess.yeecolor.activity.LoginAcitivity;
import com.goddess.yeecolor.adapter.PublicFragmentViewPagerAdapter;
import com.goddess.yeecolor.base.BaseFragment;
import com.goddess.yeecolor.tools.MyUrl;
import com.goddess.yeecolor.tools.OkttpUtils;
import com.goddess.yeecolor.tools.SharePreceUtils;
import com.goddess.yeecolor.tools.ToastUtils;
import com.goddess.yeecolor.view.dialog_progress;
import com.goddess.yeecolor.webview.PublicFragmentViewpagerWebView;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Yee3 on 2017/1/9.
 */

public class PublicFragment extends BaseFragment {
    private PublicFragmentViewPagerAdapter adapter;
    private XRecyclerView recyclerView;
    private LinearLayoutManager manager;
    private List<PublicModle> modleList=new ArrayList<>();
    //记录分页 页数
    private int page=1;
    //记录上拉下拉状态
    private String PULL_STATE="";
    //请求数据用来传参的Map
    private Map<Object,Object> map;
    //接收到的json字符串
    private String jsonString="";
    //接收到的code值,判断网络请求数据是否异常
    private int code=0;

    private dialog_progress dialog_progress;

    private LinearLayout linearLayout;

    private View mView;
    private List<String> data;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView==null){
            mView=inflater.inflate(R.layout.fragment_public,container,false);
            initFindView();
            initOnClck();
            initdatas();
        }
        return mView;
    }
    private void setProgress(){
      // recyclerView.setPullRefreshEnabled(true);
        dialog_progress=new dialog_progress(getActivity());
        dialog_progress.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog_progress.setCanceledOnTouchOutside(false);//按返回键可以关闭进度条
        //  dialog_progress.show();
    }

    public void initdatas(){
        PULL_STATE="STATE";
        initData();
    }

    /**
     * 设置View的Onlistener相关
     */
    @Override
    public void initOnClck() {
        //item点击事件
        adapter.setOnItemClickListener(new PublicFragmentViewPagerAdapter.OnItemClicklistener() {
            @Override
            public void OnItemClick(View view,int position) {
                String uuid= SharePreceUtils.getOther("user","unique");
                if(!"".equals(uuid)){
                    Intent intent=new Intent();
                    getActivity().overridePendingTransition(0,0);
                    intent.setClass(getActivity(),PublicFragmentViewpagerWebView.class);
                    intent.putExtra("id",String.valueOf(modleList.get(position).getId()));
                    intent.putExtra("webview",modleList.get(position).getWebview());
                    intent.putExtra("price",modleList.get(position).getPrice());
                    Log.e(MyUrl.TAG,"ididididi"+modleList.get(position).getId()+"position"+position);
                    startActivity(intent);
                }else{
                    Intent intent=new Intent(getContext(),LoginAcitivity.class);
                    startActivity(intent);
                }

            }
        });

        /**
         * 下拉刷新&下拉加载
         */
        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            /**
             * 下拉刷新
             */
            @Override
            public void onRefresh() {}
            /**
             * 上拉加载
             */
            @Override
            public void onLoadMore() {
                PULL_STATE="TOP";
                page++;
                initData();

            }
        });

//        /**
//         * 适配器
//         */
//        recyclerView.setAdapter(adapter);
//        recyclerView.setRefreshing(true);

    }
    /**
     * 初始化控件相关
     */
    @Override
    public void initFindView() {
        // linearLayout= (LinearLayout) mView.findViewById(R.id.linear_layout);
        /**
         * 控件初始化
         */
        recyclerView= (XRecyclerView) mView.findViewById(R.id.feagment_curriculum_recyclerview);
        manager=new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(manager);
        /**
         * 设置上拉 下拉 样式
         */
        recyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        recyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        recyclerView.setArrowImageView(R.mipmap.ic_pulltorefresh_arrow);
        recyclerView.setPullRefreshEnabled(false);


        adapter=new PublicFragmentViewPagerAdapter(modleList,getContext());
            setProgress();
    }

    /**
     * 初始化页面数据
     */
    @Override
    public void initData() {
        String url= MyUrl.COLLEGE_CURRICU;
        map=new HashMap<>();
        map.put("unique", SharePreceUtils.getOther("user","unique"));
        map.put("typed","1");
        map.put("page",page+"");
        OkttpUtils.getIntence().OkttpPost(url,map,handler,1);
    }

    /**
     * handler异步请求网络数据
     */
    String endfull="";
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                jsonString=msg.getData().getString("result");
                JSONObject object=new JSONObject(jsonString);
                code=object.getInt("code");
                if(code==100){
                    JSONArray result=object.getJSONArray("result");
                    for (int i=0;i<result.length();i++){
                        JSONObject object1=result.getJSONObject(i);
                        PublicModle modle=new PublicModle();
                        modle.setId(object1.getString("id"));
                        modle.setState(object1.getInt("state"));
                        modle.setImage(object1.getString("thumb"));
                        modle.setTitle(object1.getString("title"));
                        modle.setPrice(object1.getString("price"));
                        modle.setData(object1.getString("start_date"));
                        modle.setWebview(object1.getString("webview"));
                        modleList.add(modle);
                    }
                    JSONObject jsonObject=object.getJSONObject("extends");
                    endfull=jsonObject.getString("endfull");

                }else if(code==403){
                    JSONObject result=object.getJSONObject("result");
                    String mssg=result.getString("msg");
                    ToastUtils.toast(mssg);
                }


                if (dialog_progress.isShowing()){
                    dialog_progress.dismiss();
                }

                if(PULL_STATE.equals("TOP")){
                    recyclerView.loadMoreComplete();
                }else{

                    /**
                     * 适配器
                     */
                    recyclerView.setAdapter(adapter);
                    recyclerView.setRefreshing(true);
                }
                adapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    public void setData(List<PublicModle> modleList) {
        modleList.clear();
        this.modleList.addAll(0,modleList);
        /**
         * 适配器
         */
//        recyclerView.setAdapter(adapter);
//        recyclerView.setRefreshing(true);
        adapter=new PublicFragmentViewPagerAdapter(modleList,getContext());
        adapter.notifyDataSetChanged();
    }
}
